package cn.deepmax.anime.web.task;

import cn.deepmax.anime.web.Constant;
import cn.deepmax.anime.web.pojo.Section;
import cn.deepmax.anime.web.pojo.SectionImg;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class DownLoadTask implements Runnable{


    SectionImg img;

    public DownLoadTask(SectionImg img ) {
        this.img = img;
    }

    @Override
    public void run() {
        try{
            download();
        }catch (Exception e){
            log.error("Failed to download. "+img.getSectionIndex()+" "+img.getPage(), e);
        }
    }

    private void download()throws Exception{

        String sectionString = String.format("%04d", img.getSectionIndex());
        String pageString = String.format("%03d", img.getPage());

        File file = new File(Constant.getRootFolder()
                +File.separator
                +sectionString
                +File.separator
                +pageString
                +getSuffix());
        if(file.exists()){
            return;
        }else{
            boolean newFile = file.createNewFile();
            if(!newFile){
                log.error("Fail to create S{}-P{}", img.getSectionIndex(), img.getPage());
                return;
            }
        }
        URL url = new URL(img.getUrl());
        FileOutputStream fos =null;
        BufferedOutputStream bos = null;
        InputStream in = null;
        BufferedInputStream bin = null;
        try{
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            in = url.openConnection().getInputStream();
            bin = new BufferedInputStream(in);
            transfer(bin, bos);
        }finally {
            close(bin);
            close(in);
            close(bos);
            close(fos);
        }
        log.info("Download [S{}][P{}] ok to {}", img.getSectionIndex(), img.getPage(), file.getAbsolutePath());

    }

    private void transfer(InputStream in,OutputStream out) throws IOException {

        int size = 1024;
        byte[] buf = new byte[size];
        int read = 0;
        while ((read = in.read(buf))!=-1){
            out.write(buf, 0, read);
        }
    }

    private void close(Closeable closeable){
        if(closeable!=null) {
            try {
                closeable.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }

    private String getSuffix(){
        int index = img.getUrl().lastIndexOf(".");
        return img.getUrl().substring(index);
    }
}
